import { post, get, api, put, del, postFormDate, postBuffer } from '@/utils/request';
import { ElMessage } from 'element-plus';
import { getStorage } from '@/utils';

/**
 * data: {
 *  userBotId: 使用机器人访问时必传
 *  teamId： 使用团队模式
 *  user：userId 聊天模式必传（聊天必须登录）
 * }
 */
export const messageAdd = async ({ data, onMessage, onEnded, onOpen }: any) => {
  const teamId = getStorage('teamId');
  if (teamId) {
    data.teamId = teamId;
  }
  if (data.max_tokens) {
    // 不限制
    delete data.max_tokens;
  }
  const { data: id, errCode, message } = await post('/szjc-ai/common/messages', { ...data, stream: true });
  if (errCode !== 0) {
    ElMessage.error(message);
    return;
  }
  const eventSource = new EventSource(`${api}/szjc-ai/common/messages?id=${id}`);
  if (errCode === 0) {
    eventSource.onopen = () => {
      if (onOpen) {
        onOpen();
      }
    };
    eventSource.onerror = () => {
      onEnded();
      eventSource.close();
    };
    eventSource.onmessage = e => {
      const { end, content, index, err } = JSON.parse(e.data);

      if (onMessage) {
        onMessage({ content: content || '', index, err: err || '' });
      }
      if (end && data.n === index + 1) {
        if (onEnded) {
          onEnded();
        }
        eventSource.close();
      }
    };
  }
  return eventSource;
};
// type:1对话，2写作
// : { modelType: string; type: string }
export const chatGet = (data: any) => get('/szjc-ai/chat', data);
export const chatLogGet = (data: { chatId: string }) => get('/szjc-ai/chat/log', data);
export const chatLogDelete = (data: { chatId: string }) => post('/szjc-ai/chat/clear', data);
export const chatLogAdd = (data: {
  botId: string;
  question: string;
  answer: string;
  modelType?: string;
  chatId?: string;
  id?: string;
  conversation_id?: string;
  filePath?: any;
  ext?: any;
}) => post('/szjc-ai/chat/log', data);

interface creatImg {
  prompt: string;
  size: string;
  n: number;
  quality: string;
  style: string;
}

// ========新chat============
// 暂停, http://192.168.1.98/api/dify/dify/chat-messages/:taskId/stop
export const stopChat = (data: any) =>
  post(`/szjc-ai/dify/chat-messages/${data.taskId}/stop`, { user: data.user, botId: data.botId });

// 深度学习 subject,grade,title,subjectCatalogId
export const deepLearn = (data: any) => get('/textbook/res/sysRes', data);
// 教研计划深度学习
export const deepSection = (data: any) => get('/textbook/res/sysResBySection', data);

// AI英语听力
export const aiListen = (data: any) => post('/szjc-ai/audio', data);
export const aiListenStyle = (data: any) => post('/szjc-ai/audio/updateStyle', data);
// 获取音频
export const getAudio = (data: any) => get('/szjc-ai/audio/get', data);

// 数学 化学 科学 物理教具
export const Jiaoju = (data: any) => post('/szjc-ai/customize/jjsc', data);
// 单词消消乐
export const XXl = (data: any) => post('/szjc-ai/customize/dcxxl', data);

export const fileTypeGet = () => get(`/textbook/common/fileType`);
/**
 * 获取公共数据源
 * @param {*} bucket
 */
export const comment = (bucket: any) => get('res/knowledgeCatalog', bucket);
/**
 * 获取公共数据源缓存
 */
const commentCaches = {} as any;

/**
 * 获取公共数据源缓存(带缓存)
 * @param {*} bucket
 */
export const getCommentCache = (bucket: any) => {
  if (commentCaches[bucket]) {
    return Promise.resolve(commentCaches[bucket]);
  }
  return comment(bucket).then(res => {
    const { data } = res;
    const { data: cont } = data[0] || {};
    commentCaches[bucket] = cont;
    return cont;
  });
};
/**
 * 获取教参章节
 * @param {*} args(grade,subject,publishers:y(出版社),fascicule:1(分册),status:1)
 */
export const chapterGet = (args: any) => get('/res/chapterPoint', args);

// const q = { userId, name, project: 'hnszjcfile' };
// const headers = { 'Content-Type': 'application/octet-stream' };
// const fileInfo = await apiServer.post(`/oss/server/upload?${qs.stringify(q)}`, data, { headers });
export const strToFile = ({ buffer, str }: any) => postBuffer(`/oss/server/upload?${JSON.stringify(str)}`, buffer);

// 字典
export const getDict = (data: any) => get('/szjcbase/dict/byKeys', data);

/**
 * ai 出题上传到远程
 * */

export const userRes = (data: any) => post(`/textbook/userRes`, data);

/**
 * 创建file 存储 markdown
 * */
export const createFileSetMarkDown = (data: any) => post(`szjc-ai/common/mdToDoc`, data);

// 获取深度加载的目录
export const getDeepCatalog = (data: any) => get('/textbook/res/sysChapter', data);

// 获取出版社
export const getPublishers = () => get('/res/commondata');